from django_filters.rest_framework import FilterSet, CharFilter, NumberFilter
from ai.models import Projects
from ai.serializers import ProjectsSerializer, ProjectsCreateUpdateSerializer
from dvadmin.utils.json_response import DetailResponse
from dvadmin.utils.viewset import CustomModelViewSet


class ProjectFilterSet(FilterSet):
    name = CharFilter(field_name="name", lookup_expr="contains")
    creator_id = NumberFilter(field_name="creator_id", lookup_expr="exact")


class ProjectsView(CustomModelViewSet):
    """
        项目管理接口
        list:查询
        create:新增
        update:修改
        retrieve:单例
        destroy:删除
        """
    queryset = Projects.objects.all()
    serializer_class = ProjectsSerializer
    create_serializer_class = ProjectsCreateUpdateSerializer
    update_serializer_class = ProjectsCreateUpdateSerializer
    filter_fields = ['creator_id']
    filterset_class = ProjectFilterSet

    # 手动实现级联删除
    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        models = instance.children.all()
        request_data = request.data
        soft_delete = request_data.get('soft_delete', True)
        if soft_delete:
            instance.is_deleted = True
            instance.save()
            for model in models:
                model.is_deleted = True
                model.save()
        else:
            self.perform_destroy(instance)
            for model in models:
                self.perform_destroy(model)
        return DetailResponse(data=[], msg="删除成功")
